package com.xframe.xdal.core.tran;


import java.sql.Connection;
import java.sql.SQLException;

/**
 * 事务对象
 *
 * @author xufeng
 * @version 1.0
 * @date 2022-09-26
 */
public class DbTransaction implements IDbTransaction {
    /**
     * 连接对象
     */
    private Connection connection;

    public DbTransaction(Connection connection) {
        this.connection = connection;
    }

    @Override
    public Connection getConnection() {
        return this.connection;
    }

    /**
     * 获得一个事务级别
     *
     * @return <T>
     */
    @Override
    public int getTransactionIsolation() {
        try {
            return this.connection.getTransactionIsolation();
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }
    /**
     * 设置一个事务级别
     * @param level 事务级别
     *
     * @return <T>
     */
    @Override
    public void setTransactionIsolation(int level) {
        try {
            this.connection.setTransactionIsolation(level);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提交一个事务
     *
     * @return <T>
     */
    @Override
    public void commit() throws SQLException {
        connection.commit();
    }

    /**
     * 回滚一个事务
     *
     * @return <T>
     */
    @Override
    public void rollBack() {
        try {
            connection.rollback();
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }

    /**
     * 释放一个事务对象
     *
     * @return <T>
     */
    @Override
    public void close() {
        try {
            if (this.connection != null) {
                connection.setAutoCommit(true);
                connection.close();
                connection = null;
            }
        }catch (Exception exception){
            exception.printStackTrace();
        }

    }
}
